/**
 * 签到页面JavaScript
 */

// 签到页面管理器
window.SignManager = {
    // 签到数据
    signData: null,

    // 初始化
    init(data) {
        this.signData = data || {};
        this.initSignData();
        this.generateCalendar();
        this.bindEvents();
    },

    // 从DOM节点初始化数据
    initFromDOM() {
        // 直接从DOM获取基础数据
        this.signData = {
            today_signed: parseInt($('[data-today-signed]').data('today-signed')) || 0,
            continuous_days: parseInt($('[data-continuous-days]').data('continuous-days')) || 0,
            today_points: parseInt($('[data-today-points]').data('today-points')) || 5,
            month: $('[data-month]').data('month') || '',
            sign_stats: {
                total_days: parseInt($('#sign-stats').data('total-days')) || 0,
                month_days: parseInt($('#sign-stats').data('month-days')) || 0,
                total_points: parseInt($('#sign-stats').data('total-points')) || 0,
                month_points: parseInt($('#sign-stats').data('month-points')) || 0
            },
            sign_rules: [],
            sign_logs: []
        };

        // 提取签到规则
        $('#sign-rules-data .sign-rule').each((index, element) => {
            const $el = $(element);
            this.signData.sign_rules.push({
                day: parseInt($el.data('day')) || 1,
                points: parseInt($el.data('points')) || 5
            });
        });

        // 提取已签到日期
        $('#calendar-data .calendar-day').each((index, element) => {
            const $el = $(element);
            if (parseInt($el.data('signed'))) {
                this.signData.sign_logs.push({
                    sign_date: $el.data('date'),
                    points: 5
                });
            }
        });

        this.initSignData();
        this.generateCalendar();
        this.bindEvents();
    },

    // 绑定事件
    bindEvents() {
        // 签到按钮点击事件
        window.doSign = () => this.doSign();
    },

    // 初始化签到数据
    initSignData() {
        // 计算总积分
        let totalPoints = 0;
        if (this.signData.sign_logs && Array.isArray(this.signData.sign_logs)) {
            totalPoints = this.signData.sign_logs.reduce((total, log) => total + (log.points || 0), 0);
        }

        // 计算本月签到天数
        const monthSignCount = this.signData.sign_logs ? this.signData.sign_logs.length : 0;

        // 计算今日可得积分
        const continuousDays = (this.signData.continuous_days || 0) + 1;
        const todayPoints = this.getTodayPoints(continuousDays);

        // 更新页面显示
        $('#month-sign-count').text(monthSignCount);
        $('#today-points').text(todayPoints);
    },

    // 获取今日可得积分
    getTodayPoints(continuousDays) {
        if (!this.signData.sign_rules || !Array.isArray(this.signData.sign_rules)) {
            return 5; // 默认积分
        }

        const rule = this.signData.sign_rules.find(r => r.day === continuousDays);
        return rule ? rule.points : 5;
    },

    // 生成签到日历
    generateCalendar() {
        const now = new Date();
        const year = now.getFullYear();
        const month = now.getMonth();
        const today = now.getDate();

        // 获取当月第一天是星期几
        const firstDay = new Date(year, month, 1).getDay();
        // 获取当月天数
        const daysInMonth = new Date(year, month + 1, 0).getDate();

        const grid = $('#calendar-grid');
        grid.empty();

        // 创建签到日期集合
        const signedDates = new Set();
        if (this.signData && this.signData.sign_logs && Array.isArray(this.signData.sign_logs)) {
            this.signData.sign_logs.forEach(log => {
                if (log.sign_date) {
                    const date = new Date(log.sign_date);
                    if (date.getMonth() === month && date.getFullYear() === year) {
                        signedDates.add(date.getDate());
                    }
                }
            });
        }

        // 如果今日已签到，确保添加到签到日期中
        if (this.signData && this.signData.today_signed) {
            signedDates.add(today);
        }

        // 填充空白格子
        for (let i = 0; i < firstDay; i++) {
            grid.append('<div class="h-12 w-12"></div>');
        }

        // 填充日期格子
        for (let day = 1; day <= daysInMonth; day++) {
            const isToday = day === today;
            const isSigned = signedDates.has(day);
            const isPast = day < today;

            let classes = 'h-12 w-12 flex items-center justify-center text-sm rounded-lg transition-all duration-200 relative ';
            let content = '';
            let tooltip = '';

            if (isToday && isSigned) {
                classes += 'bg-gradient-to-br from-green-400 to-green-600 text-white shadow-lg transform scale-105 ';
                content = '<i class="fas fa-check text-lg"></i>';
                tooltip = '今日已签到';
            } else if (isToday) {
                classes += 'bg-gradient-to-br from-blue-400 to-blue-600 text-white shadow-lg ring-2 ring-blue-300 ring-opacity-50 animate-pulse ';
                content = day;
                tooltip = '今日未签到';
            } else if (isSigned) {
                classes += 'bg-gradient-to-br from-green-100 to-green-200 text-green-700 border-2 border-green-300 ';
                content = '<i class="fas fa-check"></i>';
                tooltip = `${month + 1}月${day}日已签到`;
            } else if (isPast) {
                classes += 'bg-gray-100 text-gray-400 ';
                content = day;
                tooltip = `${month + 1}月${day}日未签到`;
            } else {
                classes += 'bg-gray-50 text-gray-500 border border-gray-200 ';
                content = day;
                tooltip = `${month + 1}月${day}日`;
            }

            const dayElement = `
                <div class="${classes}" title="${tooltip}" data-day="${day}">
                    ${content}
                    ${isToday && !isSigned ? '<div class="absolute -top-1 -right-1 w-3 h-3 bg-red-500 rounded-full animate-ping"></div>' : ''}
                </div>
            `;

            grid.append(dayElement);
        }

        // 添加悬停效果
        grid.find('[data-day]').hover(
            function() {
                if (!$(this).hasClass('bg-gradient-to-br')) {
                    $(this).addClass('transform scale-105 shadow-md');
                }
            },
            function() {
                $(this).removeClass('transform scale-105 shadow-md');
            }
        );

        // 更新本月签到统计
        $('#month-sign-count').text(signedDates.size);
    },

    // 执行签到
    doSign() {
        const btn = $('#sign-btn');
        const originalText = btn.html();

        // 显示签到动画
        btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i>签到中...');

        // 添加按钮动画效果
        btn.addClass('transform scale-95');

        // 调用签到接口
        $.ajax({
            url: '/user/doSign',
            type: 'POST',
            dataType: 'json',
            success: (response) => {
                if (response.code === 1) {
                    // 签到成功动画
                    this.showSignSuccessAnimation(response.data?.points || 5);

                    // 延迟刷新页面
                    setTimeout(() => {
                        location.reload();
                    }, 2000);
                } else {
                    showError(response.msg || '签到失败', 3000);
                    btn.prop('disabled', false).html(originalText).removeClass('transform scale-95');
                }
            },
            error: (xhr) => {
                let errorMsg = '网络连接失败，请稍后重试';
                if (xhr.responseJSON && xhr.responseJSON.msg) {
                    errorMsg = xhr.responseJSON.msg;
                }
                showError(errorMsg, 3000);
                btn.prop('disabled', false).html(originalText).removeClass('transform scale-95');
            }
        });
    },

    // 显示签到成功动画
    showSignSuccessAnimation(points) {
        // 创建成功提示弹窗
        const modalHtml = `
            <div id="sign-success-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                <div class="bg-white rounded-lg p-8 max-w-sm w-full mx-4 text-center transform animate-bounce">
                    <div class="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fas fa-check text-green-500 text-3xl"></i>
                    </div>
                    <h3 class="text-xl font-bold text-gray-900 mb-2">签到成功！</h3>
                    <p class="text-gray-600 mb-4">恭喜您获得 <span class="text-green-600 font-bold">${points}</span> 积分</p>
                    <div class="flex items-center justify-center space-x-2 text-sm text-gray-500">
                        <i class="fas fa-fire text-orange-500"></i>
                        <span>连续签到 ${(this.signData.continuous_days || 0) + 1} 天</span>
                    </div>
                </div>
            </div>
        `;

        $('body').append(modalHtml);

        // 3秒后自动关闭
        setTimeout(() => {
            $('#sign-success-modal').fadeOut(300, function() {
                $(this).remove();
            });
        }, 3000);

        // 播放成功音效（如果浏览器支持）
        this.playSuccessSound();

        // 显示积分飞入动画
        this.showPointsAnimation(points);
    },

    // 显示积分飞入动画
    showPointsAnimation(points) {
        const pointsElement = $(`
            <div class="fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-50 pointer-events-none">
                <div class="bg-green-500 text-white px-4 py-2 rounded-full font-bold text-lg animate-pulse">
                    +${points}
                </div>
            </div>
        `);

        $('body').append(pointsElement);

        // 动画效果
        pointsElement.animate({
            top: '20%',
            opacity: 0
        }, 1500, function() {
            $(this).remove();
        });
    },

    // 播放成功音效
    playSuccessSound() {
        try {
            // 创建音频上下文
            const audioContext = new (window.AudioContext || window.webkitAudioContext)();

            // 创建简单的成功音效
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();

            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);

            oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
            oscillator.frequency.setValueAtTime(1000, audioContext.currentTime + 0.1);

            gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);

            oscillator.start(audioContext.currentTime);
            oscillator.stop(audioContext.currentTime + 0.3);
        } catch (e) {
            // 如果音频API不支持，忽略错误
            console.log('音频API不支持');
        }
    }
};
